package com.cyc.tools;

import com.cyc.model.User;
import com.cyc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userserice;
    @Override
    //登录成功后给账户授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了doGetAuthorizationInfo");
        //必写的类
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到登录的对象
        Subject subject = SecurityUtils.getSubject();
        //拿到当前登录的对象
        User currentUser = (User)subject.getPrincipal();
        //设置当前用户权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    @Override
    //账号登录的方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        System.out.println("执行了doGetAuthenticationInfo");

        //将账号密码封装进token
        UsernamePasswordToken token = (UsernamePasswordToken) Token;
        //连接真实的数据库，从数据库获取账户密码
        User user = userserice.login(token.getUsername());
        //连接失败
        if(user==null){
            //抛出异常
            return null;
        }
        //返回当前的用户信息给授权用
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
